package logparser.bean;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

public class CaptureSave {
	private static CaptureSave INSTANCE = null;
	private String outputDir = null;
	private DataOutputStream m_writer; 
	private int origLine = 0;
	private boolean starting = false;
	private String outputFolder;
	private ICaptureHandler handler;
	private Object mFileLock = new Object();
	
	private CaptureSave(){
		
	}
	
	public static CaptureSave getInstance(){
		if(INSTANCE == null){
			INSTANCE = new CaptureSave();
		}
		
		return INSTANCE;
	}
	
	public void setOutputDir(String dir){
		outputDir = dir;
	}
	
	public void StartCapture(IQueryProcess query) throws Exception{
		if(outputDir == null){
			return;
		}
		
		outputFolder = outputDir + "\\capture\\";
		
		String logPath = outputFolder;
		
		new File(logPath).mkdirs();
		logPath += "logcat.log";
		
		File outputFile = new File(logPath);
		m_writer = new DataOutputStream(new FileOutputStream(outputFile));
		synchronized (mFileLock) {
			m_writer.write(Parser.utf8Head);
			ParserControl.getInstance().setOutputFolder(outputFolder);
			ParserControl.getInstance().SetQueryProcessHandler(query);
			ParserControl.getInstance().processStart();
		}
		
	    origLine = 0;
		starting = true;
		System.out.println("StartCapture");
	}
	
	
	public void processLine(String line) throws IOException{
		synchronized (mFileLock) {
			origLine++;
			m_writer.write((line + "\n").getBytes());
			ParserControl.getInstance().processLine(line, origLine);
		}
	}
	
	public void StopCapture() throws IOException{
		if(starting == false){
			return;
		}
		
		m_writer.close();
		ParserControl.getInstance().processEnd();
		ParserControl.getInstance().SetQueryProcessHandler(null);
		m_writer = null;
		starting = false;
		if(handler != null){
			handler.handleFinished();
		}
		
	}
	
	
	public String getOutputFolder(){
		return outputFolder;
	}
	
	
	public void setCapturehandler(ICaptureHandler i){
		handler = i;
	}
	
	public static void writeUTF8String(DataOutputStream writer,String str) 
			throws UnsupportedEncodingException, IOException{
		writer.write(str.getBytes("UTF-8"));
	}
	
	
}
